import { Body, Controller, Get, HttpStatus, Param, ParseIntPipe, Post, Req, Res } from '@nestjs/common';
import { RechargeService } from './recharge.service';
import { ResponseUtilService } from '@app/response-util';
import { ReqAttrs } from '../../constant';

@Controller('recharge')
export class RechargeController {
    constructor(
        private readonly service:RechargeService
    ) {}


    @Get('options')
    async options() {
        const options = await this.service.options()
        return ResponseUtilService.successRes(options)
    }

    @Post('pay')
    async pay(@Body('id', ParseIntPipe) id:number, @Req() req) {
        if(id < 1) return
        const res = await this.service.recharge(id, req[ReqAttrs.USER_ID], req[ReqAttrs.CLIENT_SOURCE], req[ReqAttrs.IS_WX])
        return res == null ? ResponseUtilService.failRes() : ResponseUtilService.successRes(res)
    }


    @Post('notify/:client/:id')
    async notify(@Param('id', ParseIntPipe) id:number, @Param('client') client:string, @Body() data:any, @Res() res) {
        if(isNaN(id) || id <= 0) {
            res.status(HttpStatus.OK).send();
        }
        try {
            if(client == 'wx') {
                if(data.event_type == 'TRANSACTION.SUCCESS') {
                    const r = await this.service.notify(id, data.resource, true)
                    console.log('处理结果')
                    console.log(r)


                    if(r) {
                       res.status(HttpStatus.OK).send();
                    }else {
                        res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
                    }
                }     
                
            }else { //支付宝
                
                // if(data.trade_status == 'TRADE_SUCCESS') {
                //     const r = await this.service.notify(id, data, false)
                //     if(r) {
                //         res.status(HttpStatus.OK).send();
                //      }else {
                //          res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
                //      }
                // }
                
            }

            return
        } catch (error) {
            
        }
        
        res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
    }


    @Post('page')
    async page(@Body() query:Pagination, @Req() req) {
        let rows = await this.service.page(query, req[ReqAttrs.USER_ID])
        return ResponseUtilService.successRes(rows)
    }
}
